#include "qsqlitecontrol.h"

#include <QStringList>
#include <QSqlQuery>
#include <QSqlError>

QSqliteControl::QSqliteControl()
{
}

QSqliteControl::~QSqliteControl()
{
    close();
}

bool QSqliteControl::open(const QString &name)
{
    close();
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE",name);
    m_name=name;
    db.setDatabaseName(name);

    if(!db.open())
    {
        return false;
    }
    else
    {
        return true;
    }
}

void QSqliteControl::close()
{
    QSqlDatabase::removeDatabase(m_name);
}

void QSqliteControl::create_table(const QString &name, const QStringList &list)
{
    QString str;
    str="create table "+name+" (";
    foreach(QString s,list)
    {
        str+=(s+",");
    }
    str=str.left(str.size()-1);
    str+=")";
    exec(str);
}

QSqlQuery QSqliteControl::exec(const QString &msg)
{
    QSqlDatabase db=QSqlDatabase::database(m_name);
    QSqlQuery query(db);
    qDebug(msg.toLocal8Bit());
    if(!query.exec(msg))
    {
        qDebug(query.lastError().text().toLocal8Bit());
    }
    return query;
}

void QSqliteControl::insert(const QString &table, const QStringList &values)
{
    QString str;

    str="insert into "+table+" values(";
    foreach(const QString &v,values)
    {
        str+=("'"+v+"',");
    }
    str=str.left(str.size()-1);
    str+=")";
    exec(str);
}


void QSqliteControl::replace(const QString &table, const QStringList &values)
{
    QString str;

    str="replace into "+table+" values(";
    foreach(const QString &v,values)
    {
        str+=("'"+v+"',");
    }
    str=str.left(str.size()-1);
    str+=")";
    exec(str);
}

QStringList QSqliteControl::get_tables()
{
    QSqlDatabase db=QSqlDatabase::database(m_name);
    return db.tables();
}
